<template>
  <div class="orderList">
    <div class="layout-content">
      <Filtrate
        @selectedClassifyTags="changeClassify"
        @selectedStatusTags="changeStatus"
        @selectedDate="changeDate"
      />
    </div>
    <div class="layout-content">
      <c-table
        size="small"
        ref="orderTable"
        :columns="isPricing() ? pricingColumns : confirmColumns"
        :data="tableData.pageData"
        :total="tableData.total"
        rowKey="id"
        :loading="tableLoading"
        :expanded="isSeller() && isPricing() ? true : false"
        config
        :defaultConfig="defaultConfig"
        :filterConfig="filterConfig"
        derive
        :rowClassName="rowClassName"
        @export="exportOrders"
        @onSearch="onSearch"
        @cellClick="gotoDetail"
        @expanded="expanded"
        @onReload="reload"
        @pageChange="pageChange"
      >
        <template slot="expanded">
          <ExpandedContent :data="expandedRow" />
        </template>
        <template slot="header-l">
          <!-- 排序 -->
          <ul class="sort flex">
            <li
              class="cursor-pointer flex flex-align-c"
              :class="sortKey === idx ? 'sort-item-checked' : 'sort-item'"
              v-for="(item, idx) in sortList"
              :key="item.value"
              @click="sortClick(idx)"
            >
              <span class="title">{{ item.title }}</span>
              <template v-if="idx !== 0">
                <c-icon
                  type="shangzhang"
                  size="10"
                  v-if="sort[idx - 1]"
                ></c-icon>
                <c-icon type="xiadie" size="10" v-else></c-icon>
              </template>
            </li>
          </ul>
        </template>
        <template slot="header-r">
          <a-input-search
            v-model="searchKey"
            placeholder="请输入搜索条件关键字"
            allowClear
            @search="onSearch"
          >
            <a-select
              slot="addonBefore"
              v-model="searchKeyType"
              style="width: 100px"
            >
              <a-select-option
                :value="item.value"
                v-for="item in searchKeySelects"
                :key="item.title"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </a-input-search>
        </template>
      </c-table>
    </div>
  </div>
</template>

<script>
import Filtrate from "./components/filtrate";
import ExpandedContent from "./components/expandedContent";
import {
  querySalesConfirmOrders,
  querySalesSlideOrders,
  queryPurchaseConfirmOrders,
  queryPurchaseslideOrders
} from "@/api/order";
import {
  providerexportslideorder,
  providerexportconfirmorder,
  customerexportslideorder,
  customerexportconfirmorder
} from "@/api/order/export";
import {
  getproviderlineorderpage,
  getcustomerlineorderpage
} from "@/api/order-line";
import {
  providerexportslidelineorder,
  providerexportconfirmlineorder,
  customerexportslidelineorder,
  customerexportconfirmlineorder
} from "@/api/order-line/export";
import { providergettags } from "@/api/order/tag";
import { columns } from "./columns.js";
import { isSeller, isLine, isPricing, downloadFile } from "@/util/common";
import orderDict from "@/dict/order";
import quotationDict from "@/dict/quotation";

export default {
  name: "orderList",
  components: {
    Filtrate,
    ExpandedContent
  },
  mixins: [columns],
  data() {
    return {
      searchKey: undefined,
      searchKeyType: 2,
      searchKeySelects: [
        {
          title: "订单编号",
          value: 2
        },
        {
          title: "交易公司",
          value: 1
        },
        {
          title: "规格",
          value: 3
        }
      ],
      categoryType: undefined,
      orderStatus: undefined,
      date: {
        startTime: undefined,
        endTime: undefined
      },
      pageNum: 1,
      tableLoading: false, // 列表loading
      tableData: [],
      sortList: [
        {
          title: "待处理优先",
          value: 0
        },
        {
          title: "下单时间",
          value: 1
        },
        {
          title: "数量",
          value: 2
        },
        {
          title: "价格",
          value: 3
        }
      ],
      sort: [false, false, false],
      sortKey: 1,
      expandedId: null,
      expandedRow: {},
      tags: ""
    };
  },
  computed: {
    // 不可配置的表头
    filterConfig() {
      let res = isPricing()
        ? ["tag", "orderCode"]
        : [
            "tag",
            "orderCode",
            "futuresContract",
            "dealAmount",
            "orderDealType",
            "basePrice",
            "premium"
          ];
      return res;
    },
    // 默认表头
    defaultConfig() {
      let res = [];
      // 区分点价、确定价
      if (isPricing()) {
        res = [
          // "tag",
          "futuresContract",
          "handle",
          "createDate",
          "orderCode",
          "orderStatus",
          "companyName",
          "createdUser",
          "amount",
          "basePrice",
          "categoryName",
          "brand",
          "spec",
          "material",
          "other",
          "warehouse"
        ];
      } else {
        res = [
          // "tag",
          "handle",
          "createDate",
          "orderCode",
          "orderStatus",
          "companyName",
          "createdUser",
          "tax",
          "amount",
          "categoryName",
          "brand",
          "spec",
          "material",
          "other",
          "warehouse"
        ];
      }
      return res;
    },
    // 计算排序方式
    sortType() {
      let res;
      let sorts = [
        [1, 2],
        [3, 4],
        [5, 6]
      ];
      if (this.sortKey === 0) {
        res = undefined;
      } else {
        res = sorts[this.sortKey - 1][this.sort[this.sortKey - 1] ? 0 : 1];
      }
      return res;
    }
  },
  methods: {
    isPricing,
    isSeller,
    rowClassName(record) {
      if (record.hedgeRow) {
        return "hedgeMsgRow";
      }
    },
    // 导出
    exportOrders() {
      let request;
      if (isLine()) {
        if (this.isSeller()) {
          request = this.isPricing()
            ? providerexportslidelineorder
            : providerexportconfirmlineorder;
        } else {
          request = this.isPricing()
            ? customerexportslidelineorder
            : customerexportconfirmlineorder;
        }
      } else {
        if (this.isSeller()) {
          request = this.isPricing()
            ? providerexportslideorder
            : providerexportconfirmorder;
        } else {
          request = this.isPricing()
            ? customerexportslideorder
            : customerexportconfirmorder;
        }
      }
      request({
        // 日期范围
        startTime: this.date.startTime,
        endTime: this.date.endTime,
        categoryType: this.categoryType,
        orderStatus: this.orderStatus,
        queryOrderPriorityType: this.sortType
      }).then(res => {
        downloadFile(res);
      });
    },
    // 搜索
    onSearch(val) {
      this.searchKey = val;
      this.reload();
    },
    // 分页
    pageChange(pageNum) {
      this.pageNum = pageNum;
      this.queryOrders();
    },
    // 跳转详情
    gotoDetail({ col, record }) {
      if (col.dataIndex !== "tag" && !record.hedgeRow) {
        let name = this.$route.name + "Detail";
        this.$router.push({
          name: name,
          query: { id: record.id }
        });
      }
    },
    // 选择种类
    changeClassify(val) {
      this.$refs.orderTable.setPage(1);
      this.categoryType = val === 0 ? undefined : val;
      this.reload();
    },
    // 选择状态
    changeStatus(val) {
      this.$refs.orderTable.setPage(1);
      this.orderStatus = val;
      this.reload();
    },
    changeDate(val) {
      this.$refs.orderTable.setPage(1);
      this.date.startTime = val[0];
      this.date.endTime = val[1];
      this.reload();
    },
    // 订单操作后回调
    handleSuccess({ data }) {
      // 更新订单信息
      if (data) {
        this.tableData.pageData.forEach((item, idx) => {
          if (item.id === data.id) {
            // 没有筛选订单状态或者订单状态不变，则不需要重新请求
            if (!this.orderStatus || item.orderStatus === data.orderStatus) {
              this.$set(
                this.tableData.pageData,
                idx,
                Object.assign({}, item, data)
              );
              // 处于已完成状态，查询是否有警告信息并删除
              if (
                [
                  orderDict.pricingStatus.modifyGoods.value,
                  orderDict.pricingStatus.waitContract.value,
                  orderDict.pricingStatus.modifyPremium.value,
                  orderDict.pricingStatus.createdContract.value,
                  orderDict.pricingStatus.sellerClose.value,
                  orderDict.pricingStatus.buyerClose.value,
                  orderDict.pricingStatus.cancel.value,
                  orderDict.pricingStatus.closed.value
                ].indexOf(data.orderStatus) !== -1 &&
                item.hedgeWarningMsg &&
                this.tableData.pageData[idx + 1] &&
                this.tableData.pageData[idx + 1].hedgeRow
              ) {
                this.tableData.pageData.splice(idx + 1, 1);
              }
            } else {
              this.queryOrders();
            }
          }
        });
      } else {
        this.queryOrders();
      }
    },
    reload() {
      this.pageNum = 1;
      this.queryOrders();
      if (isSeller()) this.getTags();
    },
    // 点击排序类型
    sortClick(idx) {
      if (idx !== 0 && this.sortKey === idx) {
        this.$set(this.sort, idx - 1, !this.sort[idx - 1]);
      }
      this.sortKey = idx;
      this.queryOrders();
    },
    expanded(val) {
      if (val.expanded) {
        this.expandedId = val.record.id;
        this.expandedRow = val.record;
      }
    },
    // 查询订单
    queryOrders() {
      let request;
      switch (("name", this.$route.name)) {
        // 买家中心，点价订单
        case "buyerPricingOrder":
          request = queryPurchaseslideOrders;
          break;
        // 买家中心，确定价订单
        case "buyerConfirmOrder":
          request = queryPurchaseConfirmOrders;
          break;
        // 卖家中心，点价订单
        case "sellerPricingOrder":
          request = querySalesSlideOrders;
          break;
        // 卖家中心，确定价订单
        case "sellerConfirmOrder":
          request = querySalesConfirmOrders;
          break;
        // 卖家中心，点价线路订单
        case "sellerPricingLineOrder":
          request = getproviderlineorderpage;
          break;
        // 卖家中心，确定价线路订单
        case "sellerConfirmLineOrder":
          request = getproviderlineorderpage;
          break;
        // 买家中心，点价线路订单
        case "buyerPricingLineOrder":
          request = getcustomerlineorderpage;
          break;
        // 买家中心，确定价线路订单
        case "buyerConfirmLineOrder":
          request = getcustomerlineorderpage;
          break;
        default:
          break;
      }
      this.tableLoading = true;
      request({
        // 日期范围
        startTime: this.date.startTime,
        endTime: this.date.endTime,
        // 线路订单传参：priceType作价方式
        priceType: isLine()
          ? isPricing()
            ? quotationDict.priceType.pricing.value
            : quotationDict.priceType.confirm.value
          : undefined,
        categoryType: this.categoryType,
        orderStatus: this.orderStatus,
        queryKeyType: this.searchKey ? this.searchKeyType : undefined,
        keyWord: this.searchKey || undefined,
        queryOrderPriorityType: this.sortType,
        pageData: {
          pageNum: this.pageNum,
          pageSize: 20
        }
      })
        .then(res => {
          if (res.pageData) {
            // 对于套保订单，在后面插入一行数据，用于展示套保信息
            let pageData = [];
            res.pageData.forEach((item, idx) => {
              // 是否套保订单
              if (
                this.$tools.notEmpty(item.hedgeWarningMsg) &&
                [
                  orderDict.pricingStatus.modifyGoods.value,
                  orderDict.pricingStatus.waitContract.value,
                  orderDict.pricingStatus.modifyPremium.value,
                  orderDict.pricingStatus.createdContract.value,
                  orderDict.pricingStatus.sellerClose.value,
                  orderDict.pricingStatus.buyerClose.value,
                  orderDict.pricingStatus.cancel.value,
                  orderDict.pricingStatus.closed.value
                ].indexOf(item.orderStatus) === -1
              ) {
                pageData.push(item);
                // 用于展示套保信息的行
                pageData.push({
                  id: idx + 20,
                  hedgeRow: true,
                  disableExpand: true,
                  hedgeWarningMsg: item.hedgeWarningMsg
                });
              } else {
                pageData.push({
                  ...item,
                  disableExpand:
                    [
                      orderDict.pricingStatus.cancel.value,
                      orderDict.pricingStatus.closed.value
                    ].indexOf(item.orderStatus) === -1
                      ? false
                      : true // 已取消已关闭订单不显示展开按钮
                });
              }
            });
            res.pageData = pageData;
            this.tableData = res;
          } else {
            // 搜索结果为空时，后端返回的res为空，需要自行添加数据
            this.tableData = {
              pageData: [],
              total: 0
            };
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 获取全部标签
    getTags() {
      providergettags().then(res => {
        if (res) {
          this.tags = res.tags;
        } else {
          this.tags = "";
        }
      });
    },
    // 更新标签信息
    selectedTag(data) {
      this.tableData.pageData.forEach((item, index) => {
        if (item.id === data.id) {
          item.orderTag = data.tag.id;
          let i = item;
          this.$set(this.tableData.pageData, index, i);
        }
      });
    },
    updateTags(list) {
      this.tags = JSON.stringify(list);
    }
  },
  activated() {
    if (isSeller()) this.getTags();
    this.queryOrders();
  }
};
</script>

<style lang="scss" scoped>
.sort {
  li {
    border: 1px solid #d9d9d9;
    border-left: 0;
    padding: 0 15px;
    transition: color 0.3s, background 0.3s, border-color 0.3s;
    .title {
      line-height: 30px;
      padding-right: 6px;
    }
    .iconfont {
      margin-right: 0;
    }
  }
  li:not(.sort-item-checked):hover {
    color: var(--primary);
  }
  li:last-child {
    border-radius: 0 4px 4px 0;
  }
  li:first-child {
    border-left: 1px solid #d9d9d9;
    border-radius: 4px 0 0 4px;
  }
  .sort-item .iconfont {
    color: #ccc;
  }
  .sort-item-checked {
    color: var(--primary);
    border-color: var(--primary);
    box-shadow: -1px 0 0 0 #4d65fd;
  }
  .sort-item-checked:first-child {
    border-left: 1px solid #4d65fd;
    box-shadow: none;
  }
}
.orderTag {
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0;
  min-width: 20px;
  min-height: 20px;
  max-width: 64px;
  padding: 0 2px;
  vertical-align: bottom;
}
.c-table {
  .ant-btn-link {
    padding: 0;
  }
  .basePrice {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  ::v-deep .ant-tag {
    margin-right: 0;
  }
}
.ant-input-search {
  width: 400px;
}
::v-deep .hedgeMsgRow {
  background-color: #fffbe6;
}
</style>
